﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DPFP;
using DPFP.Capture;
using DPFP.Error;
using DPFP.Gui;
using DPFP.Processing;
using DPFP.Verification;
using System.ComponentModel;
using System.Data;
using Properties;
using IngressApp.BC;
using System.Threading;

namespace IngressApp
{
    /// <summary>
    /// Interaction logic for winHuella.xaml
    /// </summary>
    public partial class winHuella : Window, DPFP.Capture.EventHandler 
    {

        Enrollment Enroller;
        private DPFP.Capture.Capture Capturer;
        public delegate void OnTemplateEventHandler(DPFP.Template template);
        public event OnTemplateEventHandler OnTemplate;
        private byte[] fpRes;
        private char[] fpChar;
        private DPFP.Template template;
        

        private int idEmp = 0;
        public int IdEmp
        {
            get { return idEmp; }
            set { idEmp = value; }
        }

        public winHuella(int id)
        {
            IdEmp = id;
            InitializeComponent();
            Enroller = new DPFP.Processing.Enrollment();
            template = new DPFP.Template();
            Init();
        }

   

        protected DPFP.FeatureSet ExtractFeatures(DPFP.Sample Sample, DPFP.Processing.DataPurpose Purpose)
        {
            DPFP.Processing.FeatureExtraction Extractor = new DPFP.Processing.FeatureExtraction();	// Create a feature extractor
            DPFP.Capture.CaptureFeedback feedback = DPFP.Capture.CaptureFeedback.None;
            DPFP.FeatureSet features = new DPFP.FeatureSet();
            Extractor.CreateFeatureSet(Sample, Purpose, ref feedback, ref features);			// TODO: return features as a result?
            if (feedback == DPFP.Capture.CaptureFeedback.Good)
                return features;
            else
                return null;
        }
     

        #region Event handlers

        public void OnComplete(object Capture, string ReaderSerialNumber, Sample Sample)
        {

            Process(Sample);
        }

        public void OnFingerGone(object Capture, string ReaderSerialNumber)
        {
           // elipseFinger.Visibility = Visibility.Collapsed;
            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => elipseFinger.Visibility = Visibility.Collapsed), null);
            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => lblRetira.Visibility = Visibility.Collapsed), null);
           // MessageBox.Show("OnFingerGone");
        }

        public void OnFingerTouch(object Capture, string ReaderSerialNumber)
        {
           // elipseFinger.Visibility = Visibility.Visible
            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => elipseFinger.Visibility = Visibility.Visible), null);
           // MessageBox.Show("OnFingerTouch");
        }

        public void OnReaderConnect(object Capture, string ReaderSerialNumber)
        {

            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => lblLeyenda.Text = "Ingresa tu Huella"), null); 
            // MessageBox.Show("OnReaderConnect");
        }

        public void OnReaderDisconnect(object Capture, string ReaderSerialNumber)
        {
            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => lblLeyenda.Text = "Lector desconectado"), null); 
        }

        public void OnSampleQuality(object Capture, string ReaderSerialNumber, CaptureFeedback CaptureFeedback)
        {
           // MessageBox.Show("OnSampleQuality");
        }
        #endregion

        public void Init()
        {
            Enroller = new DPFP.Processing.Enrollment();			// Create an enrollment.
            UpdateStatus();

            try
            {
                Capturer = new DPFP.Capture.Capture();				// Create a capture operation.

                if (null != Capturer)
                    Capturer.EventHandler = this;					// Subscribe for capturing events.
                else
                    MessageBox.Show("Can't initiate capture operation!");
            }
            catch
            {
                MessageBox.Show("Can't initiate capture operation!");
            }

            Start();

        }

        protected void Start()
        {
            if (null != Capturer)
            {
                try
                {

                    Capturer.StartCapture();
                    MessageBox.Show("Using the fingerprint reader, scan your fingerprint.");
                }
                catch
                {
                    MessageBox.Show("Can't initiate capture!");
                }
            }
        }

        protected void Stop()
        {
            if (null != Capturer)
            {
                try
                {
                    Capturer.StopCapture();
                }
                catch
                {
                    MessageBox.Show("Can't terminate capture!");
                }
            }
        }

        protected void Process(DPFP.Sample Sample)
        {

            // Process the sample and create a feature set for the enrollment purpose.
            DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);

            // Check quality of the sample and add to enroller if it's good
            if (features != null) try
                {
                    Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => lblRetira.Visibility = Visibility.Visible), null);
                   // MessageBox.Show("The fingerprint feature set was created.");
                    Enroller.AddFeatures(features);		// Add feature set to template.
                }
                finally
                {
                    UpdateStatus();

                    // Check if template has been created.
                    switch (Enroller.TemplateStatus)
                    {
                        case DPFP.Processing.Enrollment.Status.Ready:	// report success and stop capturing
                            template = Enroller.Template;
                            
                            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => grdDone.Visibility = Visibility.Visible), null);
                            Application.Current.Dispatcher.BeginInvoke(new ThreadStart(() => lblRetira.Visibility = Visibility.Collapsed), null);
           
                            Stop();
                            break;

                        case DPFP.Processing.Enrollment.Status.Failed:	// report failure and restart capturing
                            Enroller.Clear();
                            Stop();

                            UpdateStatus();
                            OnTemplate(null);
                            Start();
                            break;
                    }
                }
        }

        private void UpdateStatus()
        {
            // Show number of samples needed.
            //MessageBox.Show(String.Format("Fingerprint samples needed: {0}", Enroller.FeaturesNeeded));
        }

        private void btnSalvar_Click(object sender, RoutedEventArgs e)
        {
            byte[] fpByte = new byte[1632];
            Enroller.Template.Serialize(ref fpByte);

            String huella = Convert.ToBase64String(fpByte);

            EmpleadoHuella obj = new EmpleadoHuella();
            obj.IdEmpleado = idEmp;
            obj.TipoHuella = 2;
            obj.Huella = huella;

            BCUpdate insEmpleadoHuella = new BCUpdate();
            MessageBox.Show(insEmpleadoHuella.update(obj,idEmp));
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
        }
    }
}
